// Copyright 2023 Srhino Co., Ltd. All rights reserved.

package webserver

import (
	"context"
	"encoding/json"
	"fmt"
	"git.ouryun.cn/lzj1/grpc-bidirectional-stream/pkg/apis/v1"
	ifacev1 "git.ouryun.cn/lzj1/grpc-bidirectional-stream/pkg/interfaces/v1"
	"io"
	"log"
	"net/http"
	"ouryun.com/web-demo/utils"
)

type Server struct {
	addr string
	port uint32
	ctx  context.Context
	gs   ifacev1.GrpcServer
}

func NewServer(addr string, port uint32, gs ifacev1.GrpcServer) *Server {
	return &Server{
		addr: addr,
		port: port,
		ctx:  context.Background(),
		gs:   gs,
	}
}

func (s *Server) SetGs(gs ifacev1.GrpcServer) {
	s.gs = gs
}

func (s *Server) Start() error {
	config := &utils.RestServerConfig{
		Name:    "stream-demo",
		Address: fmt.Sprintf("%s:%d", s.addr, s.port),
	}

	restServer := utils.NewRestServer(s.ctx, config)
	restServer.RegisterHandlerFunc("/user", s.User)
	if err := restServer.Start(); err != nil {
		return err
	}
	return nil
}

func (s *Server) User(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	respResult := utils.NewEmptyResponseResult()
	defer func() {
		if r := recover(); r != nil {
			utils.Logger.Error(r)
			respResult.Err = r.(error).Error()
			w.WriteHeader(http.StatusInternalServerError)
			if _, err := w.Write(respResult.Bytes()); err != nil {
				utils.Logger.Error(err)
			}
		}
	}()

	// 读取请求的 Body
	body, err := io.ReadAll(r.Body)
	defer r.Body.Close()

	user := &v1.UserInfo{}
	params := &v1.QueryParams{}
	if err != nil {
		utils.Logger.Error(err)
		respResult.Err = err.Error()
		w.WriteHeader(http.StatusInternalServerError)
	} else {
		// TODO 这里需要根据不同的请求，构建不同的结构体

		if err := json.Unmarshal(body, user); err != nil {
			respResult.Err = err.Error()
			w.WriteHeader(http.StatusInternalServerError)

		}

		for k, v := range r.URL.Query() {
			params.Params[k] = v[0]
		}
	}
	if respResult.Err != "" {
		if _, err := w.Write(respResult.Bytes()); err != nil {
			utils.Logger.Error(err)
		}
		return
	}

	// 构建grpc消息, 并发送到grpc客户端
	resp, err := s.gs.Request(user, params, v1.StreamMessage_REQUEST_TYPE, 0)

	log.Printf("resp:%v err:%v", resp, err)

	if err != nil {
		respResult.Err = err.Error()
		w.WriteHeader(http.StatusInternalServerError)
		if _, err := w.Write(respResult.Bytes()); err != nil {
			utils.Logger.Error(err)
		}
		return
	}

	// 数据解密
	respData, err := utils.AnyToMessage(resp.Data)

	if err != nil {
		respResult.Err = err.Error()
	} else {
		respResult.Data = respData
	}

	if _, err := w.Write(respResult.Bytes()); err != nil {
		utils.Logger.Error(err)
	}
}

func (s *Server) Callback(message *v1.StreamMessage) {
	log.Printf("callback: %v", message)
	//数据解密
	data, err := utils.AnyToMessage(message.Data)
	if err != nil {
		log.Print(err)
		return
	}
	_, err = s.gs.Request(data, nil, v1.StreamMessage_RESPONSE_TYPE, message.RequestId)
	if err != nil {
		return
	}
}
